__author__ = 'wangjc'

import smtplib
from email.mime.text import MIMEText
from email.header import Header
import os
import yaml

class MailUtil:

    def sendMail(self,receiver,msg):

        receivers = receiver  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱

        # 读取邮件配置文件
        dirPath = os.path.abspath(os.path.join(os.path.dirname("application.yaml"), os.pardir))
        print(dirPath)
        print(os.path.join(dirPath, "Caps", "application.yaml"))
        fs = open(os.path.join(dirPath, "Caps", "application.yaml"), encoding="utf-8")
        datas = yaml.load(fs, Loader=yaml.FullLoader)
        for i in datas:
            server = i["server"]
            user = i["user"]
            password = i["pass"]
            host = i["host"]
        sender = user
        # 第三方 SMTP 服务
        mail_server = server  # 设置服务器
        mail_host = host  # 设置端口
        mail_user = user  # 用户名
        mail_pass = password  # 口令
        toTemp = ''
        # 获取邮件接收人地址
        for r in receivers:
            if toTemp != '':
                toTemp = toTemp +','+ r
        print(toTemp)
        message = MIMEText(msg, 'plain', 'utf-8')
        message['From'] = Header(user, 'utf-8')  # 发送者
        message['To'] = Header(toTemp, 'utf-8')  # 接收者

        subject = '自动化测试报告'
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(mail_server, mail_host)  # 25 为 SMTP 端口号
            smtpObj.login(mail_user, mail_pass)
            smtpObj.sendmail(sender, receivers, message.as_string())
            print("邮件发送成功")
        except smtplib.SMTPException:
            print("发送邮件失败")
